import { defineStore } from 'pinia';
import { ref } from 'vue';
import { fetchSkuList } from '../services/sku';

// ---- 类型定义（精简版，后续可与真实接口对齐） ----
export interface SkuProductBase {
  code: string;
  category: string;
  name?: string;
  // 状态：保持 union，后端若返回未知值会被归一到 pending
  status: 'pending' | 'completed';
  createdAt: number;
  updatedAt: number;
  attributes: Record<string, string | { value: string | number; unit?: string }>;
  mainImageUrl?: string;
}

// 统一的状态枚举与显示文案映射（界面展示统一走这里）
export const SKU_STATUS_LABEL_MAP: Record<'pending' | 'completed', string> = {
  pending: '待维护',
  completed: '已完成'
};

// 状态显示辅助函数（可在组件里直接调用）
export function getSkuStatusLabel(status: SkuProductBase['status']): string {
  return SKU_STATUS_LABEL_MAP[status];
}

export interface BomItemMock {
  id: string;
  type: 'production' | 'packaging'; // 对应“BOM类型”：production=物料BOM, packaging=包装BOM
  seq: number;
  materialName: string;            // 物料名称（这里作为名称的默认展示）
  materialCode?: string;           // 物料编码
  category?: string;               // 物料分类
  costName?: string;               // 名称（若与 materialName 不同）
  spec?: string;
  qty: number;
  unit: string;
  lossFactor?: number;
  source?: string;
  remark?: string;
  imageUrl?: string;
  unitCost?: number;               // mock cost（单价）
  attributes?: Record<string,string>; // 行属性集合
  feeDetail?: {                    // 费用信息（弹窗展示用）
    mode: 'fixed' | 'count';
    amount: number;               // 固定金额或单价
    quantity?: number;            // 计数量
    formula?: string;             // 若有公式
    currency: string;
  };
}


interface SkuState {
  list: SkuProductBase[];
  bomMap: Record<string, BomItemMock[]>; // key: productCode
  extraFeeMap: Record<string, { harbor: number; cutting: number; labor: number }>; // 非物料成本
  packageCostMap: Record<string, { packageId: string; packageName: string; packageCode: string; cost: number }>; // 包装成本
  loading: boolean;
}

export const useSkuStore = defineStore('sku', () => {
  const state = ref<SkuState>({ list: [], bomMap: {}, extraFeeMap: {}, packageCostMap: {}, loading: false });

  // 已移除所有本地写死的测试数据；数据按需通过接口加载。
  function parseStatus(s: string): 'pending' | 'completed' {
    return s === 'completed' ? 'completed' : 'pending';
  }

  async function loadProductByCode(code: string) {
    if (!code) return;
    // 若已存在则不重复加载（可按需增加刷新参数）
    if (getProduct(code)) return;
    state.value.loading = true;
    try {
      const page = await fetchSkuList({ page: 1, pageSize: 1, invCode: code });
      const rec = page.records?.[0];
      if (!rec) return; // 未找到
      const now = Date.now();
      const prod: SkuProductBase = {
        code: rec.invCode,
        category: rec.productType || '',
        name: rec.name || rec.invCode,
        status: parseStatus(rec.status || ''),
        createdAt: now,
        updatedAt: now,
        attributes: {},
        mainImageUrl: ''
      };
      // 放入列表（若列表需要排序，可扩展）
      state.value.list.push(prod);
      // 非物料费用
      state.value.extraFeeMap[code] = { harbor: rec.port || 0, cutting: rec.cutting || 0, labor: rec.labor || 0 };
      // BOM 构建
  const bomItems = (rec.bomS || []).map((b: any, idx: number) => {
        const unitPrice = b.bom?.feeAmount || 0;  // 后端 BOM 字段：feeAmount
        const feeMode = b.bom?.feeModel || 'count';
        return {
          id: b.bom.id || `${code}-bom-${idx}`,
          type: b.bom.bomType === 'packaging' ? 'packaging' : 'production',
          seq: idx + 1,
          category: b.bom.className || '',
          materialCode: b.bom.invCode,
          materialName: b.bom.name,
          costName: b.bom.name,
          spec: '',
          qty: b.quantity || 0,
          unit: 'pcs',
          unitCost: unitPrice,
          source: '',
          lossFactor: 1,
          attributes: {},
          feeDetail: { mode: feeMode, amount: unitPrice, quantity: b.quantity || 0, currency: 'CNY' }
        };
      });
      state.value.bomMap[code] = bomItems;
    } catch (e) {
      console.error('加载产品失败', e);
    } finally {
      state.value.loading = false;
    }
  }

  function listProducts() {
    return state.value.list;
  }

  function getProduct(code: string) {
    return state.value.list.find(p => p.code === code);
  }

  function getBom(code: string) {
    return state.value.bomMap[code] || [];
  }
  function getExtraFees(code: string){
    return state.value.extraFeeMap[code] || { harbor:0, cutting:0, labor:0 };
  }
  function setExtraFees(code: string, fees: Partial<{ harbor:number; cutting:number; labor:number }>) {
    const cur = state.value.extraFeeMap[code] || { harbor:0, cutting:0, labor:0 };
    state.value.extraFeeMap[code] = { harbor: fees.harbor ?? cur.harbor, cutting: fees.cutting ?? cur.cutting, labor: fees.labor ?? cur.labor };
  }

  function getPackageCost(code: string) {
    const pkg = state.value.packageCostMap[code];
    return pkg ? { packageId: pkg.packageId, packageName: pkg.packageName, packageCode: pkg.packageCode, cost: pkg.cost } : { packageId: '', packageName: '', packageCode: '', cost: 0 };
  }

  function setPackageCost(code: string, packageInfo: { packageId: string; packageName: string; packageCode: string; cost: number }) {
    state.value.packageCostMap[code] = packageInfo;
  }

  function clearPackageCost(code: string) {
    delete state.value.packageCostMap[code];
  }

  return { state, listProducts, getProduct, getBom, getExtraFees, setExtraFees, getPackageCost, setPackageCost, clearPackageCost, loadProductByCode, getSkuStatusLabel, SKU_STATUS_LABEL_MAP };
});
